<template>
  <div class="p-8">
    <h2 class="text-xl font-bold mb-4">数据管理 / 快照与恢复</h2>
    <div class="flex gap-4 mb-6">
      <button @click="handleMakeSnapshot" class="bg-blue-500 text-white px-4 py-2 rounded-lg">手动备份快照</button>
      <button @click="loadSnapshots" class="bg-gray-200 px-4 py-2 rounded-lg">刷新快照列表</button>
    </div>
    <ul class="mb-6">
      <li v-for="item in snapshots" :key="item.timestamp" class="mb-2 flex gap-4 items-center">
        <span>时间：{{ new Date(item.timestamp).toLocaleString() }} | 备注：{{ item.note }}</span>
        <button @click="restore(item.timestamp)" class="bg-yellow-400 px-3 py-1 rounded">一键恢复</button>
      </li>
    </ul>
    <div class="text-gray-500 text-sm">所有操作均会自动快照，异常可一键回滚</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getDB, makeSnapshot, restoreSnapshot } from '@/store/db'

const snapshots = ref<any[]>([])

async function loadSnapshots() {
  const db = await getDB()
  const all = await db.getAll('backup')
  snapshots.value = all.sort((a, b) => b.timestamp - a.timestamp)
}

async function handleMakeSnapshot() {
  await makeSnapshot('手动备份')
  await loadSnapshots()
  alert('备份成功')
}

async function restore(ts: number) {
  if (confirm('确认回滚到该快照？当前数据将被覆盖！')) {
    await restoreSnapshot(ts)
    alert('恢复成功，建议刷新页面')
  }
}

onMounted(() => {
  loadSnapshots()
})
</script>
